import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/stores'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'index',
      component: () => import('@/views/index.vue'),
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/about.vue'),
    },
    {
      path: '/contact',
      name: 'contact',
      component: () => import('../views/contact.vue'),
    },
    {
      path: '/course',
      name: 'course',
      component: () => import('../views/course.vue'),
    },
    {
      path: '/library',
      name: 'library',
      component: () => import('../views/library/index.vue'),
    },
    {
      path: '/library-details/:id',
      name: 'library-details',
      component: () => import('../views/library/details.vue'),
    },
    {
      path: '/signup',
      name: 'signup',
      component: () => import('../views/signup.vue'),
    },
    {
      path: '/user-info',
      name: 'userInfo',
      component: () => import('../views/userInfo/index.vue'),
    },
    {
      path: '/user-info/edit',
      name: 'userInfoEdit',
      component: () => import('../views/userInfo/edit.vue'),
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login.vue'),
    },
    {
      path: '/select',
      name: 'select',
      component: () => import('../views/select.vue'),
    },
    {
      path: '/404',
      name: '404',
      component: () => import('../views/notfound.vue'),
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/404',
    },
  ],
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  },
})

router.beforeEach((to, from, next) => {
  const { token } = useUserStore()
  if (
    (to.name === 'signup' && !token) ||
    (to.name === 'select' && !token) ||
    (to.name === 'library' && !token) ||
    (to.name === 'userInfo' && !token) ||
    (to.name === 'userInfoEdit' && !token) ||
    (to.name === 'library-details' && !token)
  ) {
    next({ name: 'login' })
  } else {
    next()
  }
})
export default router
